package com.shanliao.version;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

import lombok.Data;
@Data
public class OperationCondition implements RequestCondition<OperationCondition> {
 
    // 路径中版本的前缀， 这里用 /v[1-9]/的形式
    private String operation;
     
    public OperationCondition(String operation){
        this.operation = operation;
    }
    @Override 
    public OperationCondition combine(OperationCondition other) {
        // 采用最后定义优先原则，则方法上的定义覆盖类上面的定义
        return new OperationCondition(other.getOperation());
    }
    @Override
    public OperationCondition getMatchingCondition(HttpServletRequest request) {
    	String operation = request.getParameter("operation");
            if(StringUtils.equalsIgnoreCase(operation, this.operation)) // 如果请求的版本号大于配置版本号， 则满足
                return this;
        return null;
    }
    /**
     * 对两个RequestCondition对象进行比较，这里主要是如果存在两个注册的一样的Mapping，
     * 那么就会对这两个Mapping进行排序，以判断哪个Mapping更适合处理当前request请求
     *
     * @param other
     * @param request
     * @return 返回-1,0,1
     */
    @Override
    public int compareTo(OperationCondition other, HttpServletRequest request) {
        // 优先匹配最新的版本号
    	if(StringUtils.equalsIgnoreCase(other.operation, this.operation)) {
    		return 1;
    	}else {
    		return -1;
    	}
    }
 
 
}